package com.itdfq.loginuser.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.itdfq.loginuser.domain.DfqUsers;
import com.itdfq.loginuser.domain.Result;
import com.itdfq.loginuser.service.RedisService;
import com.itdfq.loginuser.service.UserService;
import com.itdfq.loginuser.utils.PasswordUtils;
import com.itdfq.loginuser.utils.ThreadLocalUserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @Author: GodChin
 * @Date: 2021/8/19 17:48
 * @Blog: itdfq.com
 * @QQ: 909256107
 * @Description:
 */
@RestController
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;


    private Result result = new Result();

    @RequestMapping("/login")
    public Result login(@RequestParam(required = true, name = "username") String username,
                        @RequestParam(required = true, name = "password") String password) {
        DfqUsers dfqUsers = new DfqUsers();
        dfqUsers.setUsername(username);
        List<DfqUsers> byUser = userService.findByUser(dfqUsers);
        DfqUsers user = null;
        if (CollUtil.isEmpty(byUser)) {
            return result.setCode(-1).setMsg("用户不存在").setSuccess(false);
        }
        user = byUser.get(0);
        String password1 = PasswordUtils.getPassword(user.getPassword());
        if (!password1.equals(password)) {
            return result.setCode(-1).setMsg("密码错误").setSuccess(false);
        }
        //更新user
        updateUser(user);
        //获取token返回
        String token = makeToken(user);
        return result.setSuccess(true).setCode(200).setData(token);
    }

    @RequestMapping("/test")
    public Result test(){
        DfqUsers dfqUsers = ThreadLocalUserUtils.get();
        return result.setSuccess(true).setCode(200).setData(dfqUsers);
    }

    public String makeToken(DfqUsers useId) {
        String simpleUUID = IdUtil.simpleUUID();
        redisService.putToken(simpleUUID, useId.getId());
        return simpleUUID;
    }
    public void updateUser(DfqUsers dfqUsers){
        dfqUsers.setIsFirst(false);
        dfqUsers.setLastLoginTime(new Date());
        userService.update(dfqUsers);
    }
}
